#include "HelpWindow.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <GL/glew.h>
#include "chai3d.h"

int sub_window_id= -1;

int helpPosX=300;
int helpPosY=300;
int helpSizeX=500;
int helpSizeY=500;

float font_width = 8.f;
float font_height = 13.f;
void keySelectHelp(unsigned char key, int x, int y){
  switch (key){
  case 27: 
  case 'x':    
    glutDestroyWindow(sub_window_id);
    break;
  default:
    break;
  }
}


const char* helptext []={
  "Falcon button: Inject ink",
  "Space bar: Reset all",
  "R: Reset ink",
  "V: Reset velocity",
  "1-5: Display mode",
  "F1-F4: Fluid jet"
};

void updateGraphicsHelp(){
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glPushMatrix();
  glLoadIdentity();
  glTranslatef(0.0, (GLfloat)(glutGet(GLUT_WINDOW_HEIGHT) - 1.0), 0.0);
  glScalef(1.0, -1.0, 1.0);
  
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), 0, glutGet(GLUT_WINDOW_HEIGHT), -1, 1);
  
  glMatrixMode(GL_MODELVIEW);
  
  void* font = (void *) GLUT_BITMAP_8_BY_13;
  
  float text_y = font_height;
  for(int i = 0; i<sizeof(helptext)/sizeof(char*); i++){
    glRasterPos2f(font_width, text_y);
    int len = (int) strlen(helptext[i]);
    for (int j = 0; j < len; j++) {
      glutBitmapCharacter(font, helptext[i][j]);
    }
    text_y += font_height+2.f;
  }
  
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  
  glMatrixMode(GL_MODELVIEW);
  glPopMatrix();
  // Swap buffers
  glutSwapBuffers();
  glutPostRedisplay();
  
}


void HelpWindow(int w){
  /*
  sub_window_id = glutCreateSubWindow(w,
				  50,50,
				  50,50);*/

  int x_max = 0;
  for(int i = 0; i<sizeof(helptext)/sizeof(char*); i++){
    int len = (int) strlen(helptext[i]);
    if(len>x_max)
      x_max = len;
  }
  x_max+=2;
  glutInitWindowPosition(helpPosX, helpPosY);
  glutInitWindowSize(x_max*font_width,(sizeof(helptext)/sizeof(char*)+1)*(font_height+2));
  glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

  sub_window_id = glutCreateWindow(NULL);
  glutKeyboardFunc(keySelectHelp);
  glutDisplayFunc(updateGraphicsHelp);
}
